#define _CRT_SECURE_NO_WARNINGS 1

#include "Heap.h"

void HPInit(HP* php)
{
	assert(php);

	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}

void HPDestroy(HP* php)
{
	assert(php);

	free(php->a);
	php->a = NULL;
	php->size = php->capacity = 0;
}

void Swap(HDT* p1, HDT* p2)
{
	HDT tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustUp(HDT* pa, int child)
{
	assert(pa);

	int parnent = (child - 1) / 2;
	while (child > 0)
	{
		if (pa[child] < pa[parnent])
		{
			Swap(&pa[child], &pa[parnent]);

			child = parnent;
			parnent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void AdjustDown(HDT* pa, int size, int parent)
{
	int child = parent * 2 + 1;

	while (child < size)
	{
		if (child + 1 < size && pa[child + 1] > pa[child])
		{
			++child;
		}
		if (pa[child] > pa[parent])
		{
			Swap(&pa[child], &pa[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HPPush(HP* php, HDT x)
{
	assert(php);

	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;

		HDT* tmp = (HDT*)realloc(php->a, sizeof(php->a) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		php->a = tmp;
		php->capacity = newcapacity;
	}

	php->a[php->size] = x;
	php->size++;

	AdjustUp(php->a, php->size - 1);
}

void HPPop(HP* php)
{
	assert(php);
	assert(!HPEmpty(php));

	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	AdjustDown(php->a, php->size, 0);
}

HDT HPTop(HP* php)
{
	assert(php);
	assert(!HPEmpty(php));

	return php->a[0];
}

bool HPEmpty(HP* php)
{
	assert(php);

	return php->size == 0;
}

int HPSize(HP* php)
{
	assert(php);
	
	return php->size;
}